package de.hach.manno;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class MannOActivity extends Activity {
	private static final String TAG = "MannOActivity";
	ListView listEvents;
	MannOData mannoData;
	Cursor cursor;
	SimpleCursorAdapter adapter;

	static final String[] FROM = { MannOData.EL_MATCH, MannOData.E_PLAYTIME,
			MannOData.E_TYPE };
	static final int[] TO = { R.id.match, R.id.playtime, R.id.description };

	MannOReceiver receiver;
	IntentFilter filter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.manno);
		Log.d(TAG, "onCreate");
		listEvents = (ListView) findViewById(R.id.listEvents);
		mannoData = new MannOData(this);
		startService(new Intent(this, UpdaterService.class));

		receiver = new MannOReceiver();
		filter = new IntentFilter("de.hach.manno.NEW_DATA");

		Log.d(TAG, "UpdaterService initialized");
	}

	public void onResume() {
		super.onResume();
		Log.d(TAG, "onResume");

		// TESTING ONLY!!!!
		// Club club = new Club();
		// club.setId(10);
		// club.setName("SG Ölbronn-DüÄrrn II");
		// new PutClubToWebservice().execute(club);
		// TESTING ONLY

		// Get the data from the database
		cursor = mannoData.getEventUpdates();
		Log.d(TAG, "Found rows: " + cursor.getCount());
		startManagingCursor(cursor);

		// Create the adapter
		adapter = new SimpleCursorAdapter(this, R.layout.event_row, cursor,
				FROM, TO);
		listEvents.setAdapter(adapter);
		Log.d(TAG, "Adapter initialized");

		// Register the receiver
		registerReceiver(receiver, filter);
	}

	@Override
	public void onPause() {
		super.onPause();
		Log.d(TAG, "onPaused");

		// UNregister the receiver
		unregisterReceiver(receiver);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		mannoData.close();
		Log.d(TAG, "onDestroy");
	}

	class MannOReceiver extends BroadcastReceiver {
		private static final String TAG = "MannOReceiver";

		@Override
		public void onReceive(Context context, Intent intent) {
			cursor.requery();
			adapter.notifyDataSetChanged();
			Log.d(TAG, "onReceived");
		}

	}

	// Called first time user clicks on the menu button
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	// Called when options item is clicked
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menuClubEditor:
			startActivity(new Intent(this, ClubEditorActivity.class));
			break;
		}
		return true;

	}

}